<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/18
 * Time: 22:59
 */
namespace App\Lib\Sdk\Robot;

use App\Helper;
use App\Lib\Request\Client;
use App\Lib\Request\ResultObject;
use App\Lib\Sdk\Manager;
use App\Lib\Sdk\Robot\Service\Robot;
use App\Models\Circle;
use App\Models\Robots;
use App\Models\Send;
use App\Models\System;
use App\Models\User;
use Encore\Admin\Admin;

final class IRobot implements Robot
{
    private $client;
    private $err;

    public function __construct(Client $client)
    {
        $this->client = $client;
    }

    public function getErrorMessage() {
        return $this->err;
    }


    public function findGroupByName($name, $wxid)
    {
        if (empty($wxid)) {
            throw new \Exception("请先使用微信扫码二维码登录");
        }
        $startA = 0;
        $startB = 0;
        $ok = false;
        while (!$ok) {
            $data = $this->findGroupList($name, $wxid, $startA, $startB);
            $ok = $data['result'];
            if ($ok !== false) {
                return $ok;
            }
            $startA = $data['startA'];
            $startB = $data['startB'];
            if ($data['is_end']) {
                break;
            }
        }
        return false;
    }

    public function findGroupList($name, $wxid, $startA, $startB)
    {
        $api = "/api/Friend/GetContractList";
        $res = $this->client->post($api, [
            "currentWxcontactSeq" => $startA,
            "currentChatRoomContactSeq" => $startB,
            "wxId" => $wxid
        ])->Data;
        $lastIda = $res->CurrentWxcontactSeq;
        $lastIdb = $res->CurrentChatRoomContactSeq;
        if ($res->Contracts == null || empty($res->Contracts->toArray())) {
            return  [
                'result' => false,
                'startA' => $lastIda,
                'startB' => $lastIdb,
                'is_end' => true
            ];
        }
        $result = false;
        foreach ($res->Contracts->toArray() as $item) {
            if (strpos($item, "chatroom") !== false) {
                $detail = $this->findGroupDetail($item, $wxid);
                if ($detail == $name) {
                    $result = $item;
                    break;
                }
            }
        }
        return [
            'result' => $result,
            'startA' => $lastIda,
            'startB' => $lastIdb,
            'is_end' => false
        ];
    }

    public function findGroupDetail($item, $wxid)
    {
        $api = "/api/Friend/GetContractDetail";
        $res = $this->client->post($api, [
            "searchWxIds" => [$item],
            "wxId" => $wxid
        ])->Data->toArray();
        $res = current($res);
        return $res['nickName']['string'];
    }
    /**
     * {
    "toWxIds": [
    "string"
    ],
    "content": "string",
    "wxId": "string"
    }
     */
    public function sendMessage(array $toIds, string $content,Robots $robot)
    {
        if (empty($robot->wxid)) {
            throw new \Exception("请先使用微信扫码登录机器人");
        }
        $api = Api::message;
        $data = [
            'toWxIds' => $toIds,
            'content' => $content,
            'wxId' => $robot->wxid
        ];
        $res = $this->client->post($api, $data);
        $this->err = $res->Message;
        return $res->Success;
    }

    public function sendImgMessage(array $toIds, string $imageBase64,Robots $robot)
    {
        if (empty($robot->wxid)) {
            throw new \Exception("请先使用微信扫码登录机器人");
        }
        $api = Api::imageMessage;
        $data = [
            'toWxIds' => $toIds,
            'base64' => $imageBase64,
            'wxId' => $robot->wxid
        ];
        $res = $this->client->post($api, $data);
        return $res->Success;
    }


    public function getByUid($userId)
    {
        return Robots::where("user_id", $userId)->first();
    }

    public function createRobot($userId)
    {
        $config = System::getConfig();
        $model = new Robots();
        $model->setAttribute("user_id", $userId);
        $model->setAttribute("interval", $config->robot_interval);
        $model->setAttribute("group_max", $config->max_wx_groups);
        $model->save();
        return $model;
    }

    public function createGroup($name, Robots $robot)
    {
        if (empty($robot->wxid)) {
            throw new \Exception("用户未绑定微信");
        }
        $api = Api::createGroup;
        $res = $this->client->post($api, [
          "groupName"=> $name,
          "toWxIds" => [$robot->wxid],
          "wxId" => $robot->wxid
        ]);
        return $res;
    }

    /**
     * @param $userId
     * @return mixed
     * {
        "Data": {
            "QrBase64": "data:img/jpg;base64",
            "Uuid": "QZIn8NZnlB7i_rAkXkZU",
            "ExpiredTime": "2020-06-19T13:53:46.5135882+08:00"
        },
        "Success": true,
        "Code": "0",
        "Message": "成功"
        }
     */
    public function loginQr($robot)
    {
        $api = Api::login_qr;
        /** @var User $user */
        $user = User::where("id", $robot->user_id)->first();
        /** @var ResultObject $res */
        $res = $this->client->post($api, []);
        if ($res->getErrorCode() > 0) {
            throw new \Exception($res->getErrorMessage());
        }
        $uuid = $res->Data->Uuid;
        $expire = strtotime($res->Data->ExpiredTime);
        $robot->update([
                'uuid' => $uuid,
                'expire' => date("Y-m-d H:i:s", $expire)
            ]);
        $user->update(['uuid' => $uuid]);
        return $res->Data->QrBase64;
    }

    public function heartBeat($robot)
    {
        $wxid = $robot->wxid;
        if (empty($wxid)) {
            $this->err = "请先扫描二维码登录";
            return false;
        }
       $this->checkLogin($robot);

        $api = Api::heatBeat;
        $res = $this->client->post($api, [
            ':wxid' => $wxid
        ]);
        $this->err = $res->Message;
        return $res->Success;
    }

    public function wakeUp($robot)
    {
        if (empty($robot->wxid)) {
            return false;
        }
        $api = Api::wakeUp;
        $res = $this->client->post($api, [
            ":wxid" => $robot->wxid
        ]);
        $this->err = $res->Message;
        if ($res->Success) {
            $uuid = $res->Data->uuid;
            $user = User::where("id", $robot->user_id)->first();
            $user->update(['uuid' => $uuid]);
            $robot->update(['uuid' => $uuid]);
            return true;
        } else {
            return false;
        }
    }
    public function checkLogin_bak(Robots $robot)
    {
        $api = Api::checkLogin;
        $uuid = $robot->uuid;
        if (empty($uuid)) {
            return false;
        }
        $res = $this->client->post($api, [
            ':uuid' => $uuid
        ]);
        //$user = User::where("id", $robot->user_id)->first();
        return $res;
    }

    public function checkLogin(Robots $robot)
    {
        $api = Api::checkLogin;
        $uuid = $robot->uuid;
        if (empty($uuid)) {
            return false;
        }
        $res = $this->client->post($api, [
            ':uuid' => $uuid
        ]);
        $user = User::where("id", $robot->user_id)->first();
        if (!(bool)$res->Success) {
            switch ($res->Code) {
                case 401:
                    $this->err = "登录状态已过期，请重新扫描二维码登录!";
                  /*  $robot->update([
                        'wxid' => ''
                    ]);
                    $user->update([
                        'wxid' => ""
                    ]);*/
                    break;
                case 500:
                   $this->err = "系统错误，请稍后再试";
                   break;
            }
            return false;
        } else {
            if (!empty($res->Data->WxId)) {
                $robot->update([
                    'wxid' => $res->Data->WxId,
                    'nickname' => $res->Data->NickName
                ]);
                $user->update([
                    'wxid' => $res->Data->WxId
                ]);
            }
            if (empty($robot->wxid)) {
                $this->err =  "请使用微信扫描二维码登录!";
            }
            return $res->Success;
        }
    }

    //获取好友
    /**
     * @param $robot
     * @return mixed
     */
    public function getFriends($robot)
    {
        $wxId = $robot->wxid;
        $api = Api::friends;

        $res = $this->client->post($api, [
            "currentWxcontactSeq" => 0,
            "currentChatRoomContactSeq"=> 0,
            "wxId" => $wxId
        ]);

        return $res->Data;
    }

    /**
     * 发送1对1消息
     */
    public function send(Robots $robot, string $content, array $ids)
    {
        //$friends = $this->getFriends($robot)->toArray();
        //$ids =array_column($friends, "WxId");
        return $this->sendMessage($ids, $content, $robot);
    }

    /**
     * 发送朋友圈
     */
    public function sendFriendsCircle(Robots $robot, Circle $send)
    {
         $api = Api::sendFriendsCircle;
         //
         $link = Helper::convertCouponLinkOfCircle($send, $robot->user_id);
         $images = json_decode($send->images, true);
         $base64 = [];
         $postData = [];
         $urls = [];

         if (!empty($images)) {
             foreach ($images as $item) {
                 $base64[] = Helper::imgToBase64($item);
             }
             $urls = Manager::getSdk()->uploadWxImage($base64, $robot->wxid);
         }

         foreach ($urls as $url) {
             $postData[] =  [
                 "url" => $url,
                 "imageUrl" => $url,
             ];
         }
        $res = $this->client->post($api, [
             "type" => 1,
             "blackList"=>[],
             "withUserList"=> [],
             "mediaInfos"=> $postData,
             "title"=> $send->title,
             "contentUrl"=> "",
             "description"=> $send->title,
             "content"=> $send->content,
             "wxId"=> $robot->wxid
         ]);
        if ($res->Success) {
            $xmlObject = simplexml_load_string($res->Data->objectDesc['buffer'],
                "SimpleXMLElement", LIBXML_NOCDATA);
            $result = json_decode(json_encode($xmlObject),true);
               $this->sendComment($result['id'], $link, $robot->wxid);
        }
        return $res->Success;
    }

    public function sendComment($id, $link, $wxid)
    {
        $api = Api::comment;
        $data = [
              "id" => $id,
              "type" => 2,
              "content" => $link,
              "replyCommnetId"=> 0,
              "wxId" => $wxid
        ];
        $res = $this->client->post($api, $data);
        return $res->Success;
    }

    /**
     * @param $base64
     * @param $wxid
     *
     * {
    "Data": [{
    "BaseResponse": {
    "Ret": 0,
    "ErrMsg": {
    "String": ""
    }
    },
    "StartPos": 31894,
    "TotalLen": 31894,
    "ClientId": "1593691561933",
    "BufferUrl": {
    "Url": "http:\/\/mmsns.qpic.cn\/mmsns\/PiajxSqBRaEIRBRBoyJGfibaN8DI0cD5NxTb82PRCSTcG5Bv5tLGrMZbjd2yphM5G8\/0",
    "Type": 1
    },
    "ThumbUrlCount": 1,
    "ThumbUrls": [{
    "Url": "http:\/\/mmsns.qpic.cn\/mmsns\/PiajxSqBRaEIRBRBoyJGfibaN8DI0cD5NxTb82PRCSTcG5Bv5tLGrMZbjd2yphM5G8\/150",
    "Type": 1
    }],
    "Id": 0,
    "Type": 2
    }],
    "Success": true,
    "Code": "0",
    "Message": "\u4e0a\u4f20\u6210\u529f"
    }
     */
    public function uploadWxImage(array $base64, $wxid)
    {
        $api = Api::uploadImage;
        $res = $this->client->post($api, [
          "base64s" => $base64,
          "wxId" => $wxid
        ]);
        $data =$res->toArray();
        $response = [];
        if ($data['Code'] == 401) {
            throw new \Exception($data['Message']);
        }
        foreach ($data['Data'] as $item) {
            $response[] = $item['BufferUrl']['Url'];
        }
        return $response;
    }


}